#!/bin/bash
set -e

# ==== 配置 ====
DB_USER="nominatim"
DB_PASS="ChangeMe_StrongPwd_123"
NOMINATIM_VERSION="v4.4.0"
PBF_URL="https://download.geofabrik.de/asia/china/hebei-latest.osm.pbf"
THREADS=2 # WSL 内存有限，建议 2 线程
INSTALL_DIR="$HOME/maps"

echo "==== 1. 更新系统 & 安装依赖 ===="
sudo apt update
sudo apt install -y \
  postgresql postgresql-contrib postgis \
  build-essential cmake g++ libboost-dev libboost-system-dev libboost-filesystem-dev \
  libexpat1-dev zlib1g-dev libbz2-dev libpq-dev libproj-dev \
  libicu-dev python3 python3-pip python3-psycopg2 python3-psutil python3-setuptools \
  git curl wget

echo "==== 2. 创建数据库用户 ===="
sudo -u postgres psql -tc "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'" | grep -q 1 || \
sudo -u postgres createuser -s "$DB_USER"
sudo -u postgres psql -c "ALTER USER $DB_USER WITH PASSWORD '$DB_PASS';"

echo "==== 3. 下载 Nominatim 源码（带子模块） ===="
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"
if [ ! -d "Nominatim" ]; then
  git clone --branch "$NOMINATIM_VERSION" --recursive https://github.com/osm-search/Nominatim.git
fi

echo "==== 4. 编译 Nominatim ===="
cd "$INSTALL_DIR/Nominatim"
mkdir -p build && cd build
cmake ..
make

echo "==== 5. 下载河北省 OSM 数据 ===="
mkdir -p "$INSTALL_DIR/osm-data"
cd "$INSTALL_DIR/osm-data"
if [ ! -f "hebei-latest.osm.pbf" ]; then
  wget "$PBF_URL" -O hebei-latest.osm.pbf
fi

echo "==== 6. 导入 OSM 数据到 PostgreSQL ===="
cd "$INSTALL_DIR/Nominatim/build"
nominatim import --osm-file "$INSTALL_DIR/osm-data/hebei-latest.osm.pbf" \
  --threads "$THREADS" \
  --account "$DB_USER" \
  --dbname nominatim \
  --password "$DB_PASS" \
  --enable-diff-updates

echo "==== 7. 启动 Nominatim API 服务（端口 8080） ===="
echo "你可以用 Ctrl+C 停止服务"
nominatim serve --address 0.0.0.0 --port 8080
